﻿#include <Windows.h>

#include <QCloseEvent>
#include <QThread>
#include <QTimer>
#include <QMainWindow>

#include "customprogress.h"
#include "ui_customprogress.h"
#include "threadfunction.h"

CustomProgress::CustomProgress(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CustomProgress)
{
    ui->setupUi(this);
    setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::Tool);
    setWindowModality(Qt::ApplicationModal);
    setFixedSize(width(), height());
}

CustomProgress::~CustomProgress()
{
    delete ui;
}

CustomProgress *CustomProgress::startAProgress(const QString &title)
{
    CustomProgress *p = nullptr;
    Custom::runInMainThread([&p, title]()
    {
        p = new CustomProgress();
        p->setWindowTitle(title);
        p->showInProgress();
        QObject::connect(qApp, &QApplication::aboutToQuit, p, &CustomProgress::deleteLater);
    }, true);
    return p;
}

void CustomProgress::stopAProgress(CustomProgress *p)
{
    Custom::runInMainThread([p]()
    {
        p->finishProgress();
        p->deleteLater();
    }, true);
}

void CustomProgress::showInProgress()
{
    ui->progressBar->setValue(0);
    ui->progressBar->setMaximum(0);
    show();
    ::SetWindowPos(HWND(winId()), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
    ::SetWindowPos(HWND(winId()), HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
}

void CustomProgress::finishProgress()
{
    m_bFinished = true;
    accept();
}

void CustomProgress::closeEvent(QCloseEvent *e)
{
    if (m_bFinished)
    {
        QDialog::closeEvent(e);
    }
    else
    {
        e->ignore();
    }
}
